<?php


namespace Beerus\Modules\SuperSubsidy\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\SuperSubsidy\YouZanBrandItemModel;
use Biz\model\SuperSubsidy\YouZanBrandUserModel;
use Biz\model\SuperSubsidy\YouZanDeliverRecordModel;
use Biz\model\SuperSubsidy\YouZanOrders;
use Biz\service\SuperSubsidy\YouZanBrand;
use Biz\service\SuperSubsidy\YouZanDeliver;
use Biz\service\SuperSubsidy\YouZanOrder;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use PHPExcel_Cell_DataValidation;
use PhpOffice\PhpSpreadsheet\IOFactory;

class SubsidyBrandOrderController extends Controller
{
    const PAGE_SIZE = 20;

    public function orderList(Request $request, Content $content)
    {
        Admin::script($this->reloadOrderScript());
        $params = $request->all();
        $search_params = http_build_query($params);
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        $where = $this->getOrderCondition($params);
        list($list, $total) = YouZanOrder::searchBrandOrder(null, $page, $pageSize, $where);
        $brandOption = YouZanBrandUserModel::selectByWhere([], ['id', 'brand_name']);
        $brandOption = array_column($brandOption, 'brand_name', 'id');
        $gridModel = new pGridDataModel($list, $total, ['perPage' => $pageSize]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $brandOption, $search_params) {
            $grid->tools(function ($tools) use ($search_params) {
                $tools->append('<div class="btn-group" style="margin-right: 10px">
<a class="btn btn-sm btn-twitter" title="导出订单" href="' . url('/admin/SuperSubsidy/brand/orderList/export?' . $search_params) . '" target="_blank">
<i class="fa fa-download"></i><span class="hidden-xs">导出订单</span></a></div>');
                $tools->append('<div class="btn-group" style="margin-right: 10px">
<a class="btn btn-sm btn-twitter reload-data" title="更新近两个小时变化订单" href="javascript:void(0);">
<i class="fa fa-refresh"></i><span class="hidden-xs">更新近两个小时变化订单</span></a></div>');
            });
            $grid->filter(function (Grid\Filter $filter) use ($brandOption) {
                $filter->disableIdFilter();
                $filter->expand();//默认展开
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($brandOption) {
                    $filter->equal('brand_user_id', '品牌账户')->select($brandOption);
                    $filter->equal('tid', '订单编号');
                    $filter->equal('oid', '订单明细id');
                    $filter->between('created_time', '下单时间')->date();
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->equal('item_id', '有赞商品id');
                    $filter->equal('title', '商品名称');
                    $filter->equal('is_deliver_goods', '发货状态')->select([0 => '未发货', 1 => '已发货']);
                });
            });
            //$grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableBatchActions();
            $grid->fixColumns(2, -2);
            $grid->column('tid', '订单编号');
            $grid->column('oid', '订单明细id');
            $grid->column('brand', '品牌');
            $grid->column('item_id', '商品id');
            $grid->column('is_deliver_goods', '商品发货状态')->display(function () {
                return $this->is_deliver_goods ? '已发货' : '未发货';
            });
            $grid->column('refund_state', '商品退款状态')->display(function () {
                return $this->refund_state ? YouZanOrders::REFUND_STATE_MAP[$this->refund_state] : '';
            });
            $grid->column('refund_time', '商品退款时间')->display(function () {
                return strtotime($this->refund_time) > 0 ? $this->refund_time : '';
            });
            $grid->column('title', '商品名称');
            $grid->column('alias', '商品别名');
            $grid->column('item_barcode', '商品条码');
            $grid->column('sku_id', '规格id');
            $grid->column('sku_barcode', '规格条码');
            $grid->column('express_name', '商品发货物流公司');
            $grid->column('express_no', '商品发货物流单号');
            $grid->column('num', '商品数量');
            $grid->column('payment','实际支付金额');
            $grid->column('commission','订单结算价');
            $grid->column('sku_properties_name', '商品规格');
            $grid->column('supply_price', '供货价');
            $grid->column('pay_time', '付款时间')->display(function () {
                return strtotime($this->pay_time) > 0 ? $this->pay_time : '';
            });
            $grid->column('receiver_name', '收货人');
            $grid->column('receiver_tel', '收货人手机号');
            $grid->column('delivery_address', '收货地址')->display(function () {
                return $this->delivery_province . $this->delivery_city . $this->delivery_district . $this->delivery_address;
            });
            $grid->column('created_time', '下单时间');
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->prepend('<a class="fa fa-refresh refresh-order" data-id="' . $actions->row->tid . '" href="javascript:void(0);">更新</a>');
            });
        });
        $tab = new Tab();
        $tab->add('超级补贴 | 订单列表', $grid->render(), true);
        $tab->addLink('超级补贴 | 发货记录', url('/admin/SuperSubsidy/brand/deliverList'));
        $content->row($tab);
        return $content
            ->header("超级补贴 | 订单列表")
            ->description(' ')
            ->breadcrumb(['text' => '超级补贴 | 订单列表', 'url' => url('/admin/SuperSubsidy/brand/orderList')], ['text' => '订单列表']);
    }

    public function orderExport(Request $request)
    {
        try {
            $params = $request->all();
            $where = $this->getOrderCondition($params);
            YouZanOrder::exportOrderData(null, $where, '导出订单' . date('YmdHis'), 5000);
        } catch (\Exception $exception) {
            Log::error('导出异常', $exception);
        }
    }

    public function orderCreate(Request $request, Content $content)
    {
        $form = new Form([]);
        $form->textarea('tids', '订单编号')->help('一行一个订单编号')->rows(20)->required();
        $form->action(url('/admin/SuperSubsidy/brand/orderList/postCreate'));
        $content->row($form);
        return $content
            ->header("超级补贴 | 创建订单")
            ->description(' ')
            ->breadcrumb(['text' => '超级补贴 | 订单列表', 'url' => url('/admin/SuperSubsidy/brand/orderList')], ['text' => '创建订单']);
    }

    public function postCreate(Request $request)
    {
        $tids = $request->input('tids', '');
        if ($tids) {
            $tidsArr = explode("\n", $tids);
            foreach ($tidsArr as $tid) {
                $tid = str_replace("\r", '', $tid);
                $tid = trim($tid);
                if ($tid) {
                    YouZanOrder::searchCreateOrder(null, null, $tid);
                }
            }
        }
        $success = new MessageBag([
            'title' => '添加订单成功'
        ]);
        return redirect(url('/admin/SuperSubsidy/brand/orderList'))->with(compact('success'));
    }

    public function getOrderCondition($params)
    {
        $brandUserId = $params['brand_user_id'] ?? null;
        $brandUserId = !empty($brandUserId) ? $brandUserId : null;
        $itemId = $params['item_id'] ?? '';
        $tid = $params['tid'] ?? '';
        $oid = $params['oid'] ?? '';
        $title = $params['title'] ?? '';
        $isDeliverGoods = $params['is_deliver_goods'] ?? '';
        $isDeliverGoods = (strlen($isDeliverGoods) > 0) ? $isDeliverGoods : null;

        $start = $params['created_time']['start'] ?? null;
        $end = $params['created_time']['end'] ?? null;
        if ($start && $end && strlen($start) > 0 && strlen($end) > 0) {
            $where['created[>=]'] = $start;
            $end = date('Y-m-d', strtotime('+1 days', strtotime($end)));
            $where['created[<]'] = $end;
        }

        $itemId = trim($itemId);
        $tid = trim($tid);
        $oid = trim($oid);
        $title = trim($title);
        if ($tid) {
            $where['tid'] = $tid;
        }
        if ($oid) {
            $where['oid'] = $oid;
        }
        if ($itemId) {
            $where['item_id'] = $itemId;
        }
        if ($title) {
            $where['title[~]'] = $title;
        }
        if ($brandUserId) {
            $where['brand_user_id'] = $brandUserId;
        }
        if (!is_null($isDeliverGoods)) {
            $where['is_deliver_goods'] = $isDeliverGoods;
        }
        $where['ORDER'] = ['id' => 'DESC'];
        return $where;
    }

    private function reloadOrderScript()
    {
        return <<<SCRIPT
        $('.reload-data').unbind('click').click(function(){
            let url = '/admin/SuperSubsidy/brand/orderList/reload';
            let params = {};
            $.ajaxSettings.async = true;
            $.post(url, params , function (e) {
                 toastr.success(e.title);
                 setTimeout(function () {
                    parent.window.location.reload();
                 }, 2000);
            });
        });
        $('.refresh-order').unbind('click').click(function(){
            var id= $(this).data('id');
            let url = '/admin/SuperSubsidy/brand/orderList/reload?tid='+id;
            let params = {};
            $.ajaxSettings.async = true;
            $.post(url, params , function (e) {
                 toastr.success(e.title);
                 setTimeout(function () {
                    parent.window.location.reload();
                 }, 2000);
            });
        });
SCRIPT;
    }

    public function reloadOrder(Request $request)
    {
        try {
            $tid = $request->input('tid', null);
            $tid = !empty($tid) ? $tid : '';
            $endUpdate = date('Y-m-d H:i:s');
            $startUpdate = date('Y-m-d H:i:s', strtotime('-2 hours', strtotime($endUpdate)));
            list($allCount, $searchAlltids) = YouZanOrder::searchCreateOrder($startUpdate, $endUpdate, $tid);
            if (empty($tid)) {
                $startUpdate = strtotime('-2 hours');
                $endUpdate = time();
                list($refundCount, $searchRefundtids) = YouZanOrder::searchRefundOrders($startUpdate, $endUpdate, false, $searchAlltids);
                $allCount = $allCount + $refundCount;
            }
            $success = new MessageBag([
                'title' => '刷新订单成功,更新' . $allCount . '条订单'
            ]);
        } catch (\Exception $e) {
            $success = new MessageBag([
                'title' => '刷新失败,信息:' . $e->getFile() . $e->getLine() . $e->getMessage()
            ]);
        }
        return response()->json($success);
    }

}